
import datetime

from django.db.models import Q
from django.shortcuts import render

from django.views import View
from django import http
import json

from homes.models import House
from orders.models import Order

from utils.response_code import RETCODE

from utils.views import LoginRequiredJSONMixin


class OredersView(LoginRequiredJSONMixin, View):
    '''添加订单'''
    def post(self, request):
        '''保存订单信息'''
        #接受参数
        json_dict = json.loads(request.body.decode())
        house_id = json_dict.get('house_id')
        start_date = json_dict.get('start_date')
        end_date = json_dict.get('end_date')
        #校验参数
        if not all([house_id, start_date, end_date]):
            return http.JsonResponse({'errno': RETCODE.PARAMERR, 'errmsg': '参数不完整'})

        if start_date > end_date:
            return http.JsonResponse({'errno': RETCODE.PARAMERR, 'errmsg': '时间格式错误'})
        try:
            if start_date:
                start_date = datetime.datetime.strptime(start_date, '%Y-%m-%d').date()
            if end_date:
                end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d').date()
            days = (end_date - start_date).days + 1
        except:
            return http.HttpResponseForbidden('日期参数有误')

        #校验房屋是否存在
        try:
            house = House.objects.get(id=house_id)
        except Exception as e:
            return http.JsonResponse({'errno': RETCODE.PARAMERR, 'errmsg': '获取房屋信息失败'})
        #预订的房屋是否是房东自己的
        user = request.user
        user_id = user.id
        if user_id == house.user_id:
            return http.JsonResponse({'errno': RETCODE.PARAMERR, 'errmsg': '不能预订自己的房屋'})

        # 选择预订日期,如果在该日期有其他人预订,那么不可预订
        # 查询该房屋下的所有订单
        orders = Order.objects.filter(house_id=house_id)
        if orders:
            # 如果该房屋下有订单查询是否有冲突订单
            if start_date and end_date:
                chongtu_order = Order.objects.filter(Q(begin_date__lte=start_date, end_date__gte=start_date)
                                                     |Q(begin_date__lte=end_date,end_date__gte=end_date))
            elif start_date:
                chongtu_order = Order.objects.filter(Q(end_date__gt=start_date))
            elif end_date:
                chongtu_order = Order.objects.filter(Q(begin_date__lt=end_date))
            else:
                chongtu_order = None

            if chongtu_order:
                # 如果查询到有冲突订单，则不能预定
                return http.JsonResponse({'errno': 1, 'errmsg':'此房间已被预定'})
                # return http.HttpResponseForbidden('此房间已被预定')

        # 该房屋下没有冲突订单，可以直接下单

        #订单总额
        amount = days * house.price

        #保存订单数据
        try:
            order = Order.objects.create(
                house_id=house_id,
                user_id=user_id,
                begin_date=start_date,
                end_date=end_date,
                days=days,
                house_price=house.price,
                amount=amount
            )
            order_id = order.id
            order.save()
        except Exception as e:
            return http.JsonResponse({'errno': RETCODE.PARAMERR, 'errmsg': '订单添加失败'})
        return http.JsonResponse({'errno': RETCODE.OK, 'errmsg': '订单添加成功', 'data': order_id})


        # 接受参数
    def get(self, request):
        role = request.GET.get('role')
        user = request.user
        user_id = user.id
        # 判断登录用户的身份
        if 'landlord' == role:
            # 以房东的身份查询
            houses = House.objects.filter(user_id=user_id)
            house_ids = [house.id for house in houses]
            # 查询预订了自己房子的订单
            orders = Order.objects.filter(house_id__in=house_ids)
        else:
            orders = Order.objects.filter(user_id=user_id).order_by('-create_time')
        # 将订单数据转化为字典数据
        data = {}
        orders_dict_list = []
        if orders:
            for order in orders:
                orders_dict_list.append({
                    'amount': order.amount*100,
                    'comment': order.comment,
                    'ctime': order.create_time.date(),
                    'days': order.days,
                    'end_date': order.end_date,
                    'img_url': 'http://q18unh765.bkt.clouddn.com/'+order.house.index_image_url,
                    'order_id': order.id,
                    'start_date': order.begin_date,
                    'status': Order.ORDER_STATUS_ENUM[order.status],
                    'title': order.house.title,
                })
        data['orders'] = orders_dict_list
        return http.JsonResponse({'errno': RETCODE.OK, 'errmsg': '操作成功', 'data': data})

class OrderStatasView(LoginRequiredJSONMixin, View):
    '''修改订单状态'''
    def put(self, request, order_id):
        #接收参数
        json_dict = json.loads(request.body.decode())
        if not json_dict:
            return http.JsonResponse({'errno': RETCODE.PARAMERR, 'errmsg': '参数错误'})
        #action接单还是拒单
        action = json_dict.get('action')
        if action not in ('accept', 'reject'):
            return http.JsonResponse({'errno': RETCODE.PARAMERR, 'errmsg': '参数错误'})
        try:
            #根据订单号查询订单，并且要求订单状态处于待接单
            orders = Order.objects.filter(id=order_id, status=0)
        except Exception as e:
            return http.JsonResponse({'errno': RETCODE.PARAMERR, 'errmsg': '获取订单数据失败'})
        if action == 'accept':
            for order in orders:
                order.status = Order.ORDER_STATUS["WAIT_COMMENT"]
                order.save()
        elif action == 'reject':
            reason = json_dict.get('reason')
            if not reason:
                return http.JsonResponse({'errno': RETCODE.PARAMERR, 'errmsg': '参数错误'})
            for order in orders:
                order.status = Order.ORDER_STATUS["REJECTED"]
                order.comment = reason
                order.save()

        return http.JsonResponse({'errno': RETCODE.OK, 'errmsg': '操作成功'})

class OrderCommentView(LoginRequiredJSONMixin, View):
    '''订单评论'''
    def put(self, request, order_id):
        # 接收参数
        json_dict = json.loads(request.body.decode())
        comment = json_dict.get('comment')
        user_id = request.user.id
        if not comment:
            return http.JsonResponse({'errno': RETCODE.PARAMERR, 'errmsg': '参数错误'})
        try:
            orders = Order.objects.filter(user_id=user_id, status=3)
        except Exception as e:
            return http.JsonResponse({'errno': RETCODE.PARAMERR, 'errmsg': '获取订单数据失败'})
        try:
            for order in orders:
                house = order.house
                order.status = Order.ORDER_STATUS['COMPLETE']
                order.comment = comment
                order.save()
                house.order_count += 1
                house.save()
        except Exception as e:
            return http.JsonResponse({'errno': RETCODE.DBERR, 'errmsg': '操作失败'})
        return http.JsonResponse({'errno': RETCODE.OK, 'errmsg': '操作成功'})














